<template>
  <div id="app" v-loading="loading">
    <!--    <h1>Ticket</h1>-->
    <!--    <h2>Office Master</h2>-->
    <!--    <h3>请输入信息获取通行证</h3>-->
    <h2>Enter your details to get ticket</h2>
    <!--    Ticket-->
    <!--    Office Master-->
    <!--    请输入信息获取通行证-->
    <div class="content">
      <div class="input">
        <div class="right">
          <!--        选取上传照片-->
          <!--          <img :src="previewImageUrl" alt="预览图" style="width: 100%">-->
          <el-upload
              ref="uploadRef"
              class="avatar-uploader"
              :action="actionUrl"
              :auto-upload="false"
              :before-upload="handleBeforeUpload"
              limit="1"
              name="picture"
              :on-success="handleAvatarSuccess"
              :on-change="handleUploadChange"
              :on-exceed="handleExceed"
              :on-error="handleError"
          >
            <div class="zhang"><img src="./assets/imgs/zhang.jpg"></div>
            <div class="el-upload__text">
              Add a photo
            </div>
            <el-icon size="100">
              <Plus/>
            </el-icon>
          </el-upload>
        </div>
        <div class="left">
          <!--        姓名 职务-->
          <el-form :model="form" label-width="80px" size="large" label-suffix=":" label-position="left" :rules="rules">
            <el-form-item label="Name" prop="name">
              <el-input v-model="form.name" placeholder="Please enter your name"></el-input>
            </el-form-item>
            <el-form-item label="Position" prop="job">
              <el-input v-model="form.job" placeholder="Please enter your position"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="id-pictrue"><img src="./assets/imgs/id.jpg"></div>
    </div>
    <div class="btn">
      <el-button color="#be8c97" style="color: #fff" type="primary" size="large" @click="getPass">Get Ticket</el-button>
    </div>
    <h6 style="margin-top: 50px;color:#be8c97;">Tips:This e-ID card is for commemorative purposes only,for actual tickets please visit Eventbrite.</h6>
    <el-dialog
        title="Your ticket"
        v-model="isShowCard"
        width=""
        :before-close="handleClose">
      <Card v-show="isShowCard" ref="cardRef" :front-img="resImageUrl"/>
      <!--      <div style="width: 300px;height: 300px;">去111</div>-->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">Cancel</el-button>
          <el-button type="primary" @click="downImg">
            Download Ticket
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, ref, nextTick} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import Card from './components/Card/Card.vue'

const form = ref({
  name: '',
  job: '',
  picture: ''
})
const rules = ref({
  name: [
    {required: true, message: 'Please enter your name', trigger: 'blur'}
  ],
  job: [
    {required: true, message: 'Please enter your position', trigger: 'blur'}
  ],
  picture: [
    {required: true, message: 'Please upload the photo', trigger: 'blur'}
  ]
})
const isShowCard = ref(false)
const resImageUrl = ref('http://localhost:8000/good/images/d4438eaa14b75d277df863dc82f2750a')
const cardRef = ref(null)
const loading = ref(false)

function handleClose(done) {
  isShowCard.value = false
  // done()
}

function handleUploadChange(file, fileList) {
  console.log('handleUploadChange', file, fileList)
  form.value.picture = file.name
}

function handleExceed(files, fileList) {
  uploadRef.value.clearFiles()
  nextTick(() => {
    uploadRef.value.handleStart(files[0])
  })
}

function handleError(err, file, fileList) {
  console.log('handleError', err, file, fileList)
  ElMessage.error('Upload failed!')
  loading.value = false
}

function downImg() {
  nextTick(() => {
    // 获取图片和文本
    const imageUrl = resImageUrl.value // 替换为实际的图片URL
    const text = '123456';

    // 创建一个 canvas 元素
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    // 创建一个 Image 元素，用于加载图片
    const img = new Image();
    img.crossOrigin = 'Anonymous'; // 处理跨域图片
    img.src = imageUrl;

    img.onload = () => {
      // 设置 canvas 的尺寸
      const canvasWidth = img.width;
      const canvasHeight = img.height + 50; // 考虑到文字的高度，增加 50px 的高度

      canvas.width = canvasWidth;
      canvas.height = canvasHeight;

      // 绘制白色背景
      ctx.fillStyle = '#ffffff';
      ctx.fillRect(0, 0, canvasWidth, canvasHeight);

      // 绘制图片
      ctx.drawImage(img, 0, 0, canvasWidth, img.height);

      // 绘制文本
      ctx.font = 'bold 14px Arial';
      ctx.fillStyle = '#000';
      ctx.textAlign = 'center'; // 文本水平居中
      ctx.textBaseline = 'top';

      // 设置文本距离图片底部的边距
      const textMargin = 10;
      const textX = canvasWidth / 2; // 文本横向居中
      const textY = img.height + textMargin;

      ctx.fillText(text, textX, textY);

      // 复制 canvas 内容到剪贴板
      canvas.toBlob((blob) => {
        const clipboardItem = new ClipboardItem({'image/png': blob});

        navigator.clipboard.write([clipboardItem]).then(() => {
          ElMessage.info('下载中...')
        });
      });
      // 创建下载链接
      const link = document.createElement('a');
      link.href = canvas.toDataURL('image/png');
      link.download = 'pass.png';

      // 将链接添加到页面
      document.body.appendChild(link);

      // 触发链接点击事件
      const clickEvent = new MouseEvent('click', {
        bubbles: true,
        cancelable: false,
        view: window
      });

      link.dispatchEvent(clickEvent);

      // 移除链接
      document.body.removeChild(link);
    };
  });

  // canvas.toBlob((blob) => {
  //   const clipboardItem = new ClipboardItem({'image/png': blob});
  //   navigator.clipboard.write([clipboardItem]).then(() => {
  //     ElMessage.info('下载中...')
  //   });
  // });

  // // 创建下载链接
  // const link = document.createElement('a');
  // link.href = canvas.toDataURL('image/png');
  // link.download = 'pass.png';
  //
  // // 将链接添加到页面
  // document.body.appendChild(link);
  //
  // // 触发链接点击事件
  // const clickEvent = new MouseEvent('click', {
  //   bubbles: true,
  //   cancelable: false,
  //   view: window
  // });
  //
  // link.dispatchEvent(clickEvent);
  //
  // // 移除链接
  // document.body.removeChild(link);
}

const handleAvatarSuccess = (
    response,
    uploadFile
) => {
  resImageUrl.value = String(response)
  loading.value = false
  isShowCard.value = true
  ElMessage.success('Pass obtained successfully!')
  console.log('imageUrl', form.value.picture)
  // cardRef.value.stopMove()
  // isShowCard.value = false
  form.value.picture = ''
  form.value.name = ''
  form.value.job = ''
  uploadRef.value.clearFiles()
}
const previewImageUrl = ref('')
const fileList = ref([])

function handleBeforeUpload(file) {
  console.log('handleBeforeUpload', file)
  // 限制上传的文件类型为jpg/png
  const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJPGorPNG) {
    ElMessage.error('只能上传JPG/PNG格式的图片');
    return false;
  }

  // 限制上传的文件大小为5MB
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB');
    return false;
  }

  // 读取文件内容并显示预览图像
  const reader = new FileReader();
  reader.onload = () => {
    previewImageUrl.value = reader.result;
    console.log(previewImageUrl.value, fileList.value)
  };
  reader.readAsDataURL(file);

  // return false; // 阻止文件上传
}

const uploadRef = ref(null)
const actionUrl = computed(() => {
  return `http://154.221.30.16:8000/upload/picture?name=${form.value.name}&position=${form.value.job}`
})

function getPass() {
  if (!form.value.name || !form.value.job) {
    ElMessage.error('Please fill in the name and job!')
    return
  }
  if (!form.value.picture) {
    ElMessage.error('Please upload the photo!')
    return
  }
  uploadRef.value.submit()
  loading.value = true
  // isShowCard.value = true
  // cardRef.value.startMove()
  // setTimeout(() => {
  //   resImageUrl.value = 'http://localhost:8000/good/images/2289fcbd8179d8060f70d5779cf28905'
  // }, 3000)
}
</script>

<style lang="less">
@font-face {
  font-family: 'CustomFont'; /* 自定义字体名称 */
  src: url('@/assets/方正楷体简体.ttf'); /* 字体文件的URL路径 */
}

#app {
  font-family: "CustomFont", "FangZheng KaiTi", KaiTi, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

h2 {
  //text-align: center;
}

.input {
  display: flex;
  justify-content: space-around;
  align-items: center;
  //margin: 80px auto 50px auto;
  width: 50%;
}

.avatar-uploader .el-upload {
  //bcakground-color: blue;
  flex-direction: column;
  padding: 80px 60px;
  border: 1px dashed #d9d9d9;
  position: relative;
}

.content .id-pictrue {

}

.content {
  display: flex;
  justify-content: space-around;
  //position: relative;
  margin-bottom: 40px;
}

.id-pictrue img {
  width: 240px;
  height: 400px;
  position: relative;
  top: -120px;
}

.zhang img {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  position: absolute;
  z-index: 1;
  bottom: 0;
  right: 0;
  transform: translate(50%, 50%);
}

.el-dialog {
  //min-width: 550px;
}

//手机屏幕
@media (max-width: 992px) {
  .id-pictrue img {
    width: 188px;
    height: 314px;
    position: absolute;
    top: 12px;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  #app {
    margin-top: 188px;
  }

  h2 {
    font-size: 20px;
  }

  .avatar-uploader .el-upload {
    padding: 20px 10px;
  }

  .content .input {
    width: 100%;
  }

  .zhang img {
    width: 60px;
    height: 60px;
  }

  .input .left {
    margin-left: 10px;
  }

  .el-form-item {
    flex-direction: column;
    margin-bottom: 0px;
  }

  .el-dialog {
    min-width: 340px;
  }

  :deep(.el-upload-list) {
    width: 150px;
  }
}
</style>
